package and.example.addresscontacts;

import and.example.actionmenu.ActionItem;
import and.example.actionmenu.QuickAction;
import and.example.adapter.ContactAdapter;
import and.example.data.DatabaseConnector;
import and.example.interfaces.IArguments;
import android.app.AlertDialog.Builder;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Toast;

@SuppressWarnings("deprecation")
public class MainActivity extends ListActivity implements IArguments {

	ContactAdapter adapter;
	Cursor c;
	DatabaseConnector data;

	QuickAction quickAction;
	private static long _id = 0;
	ImageView imageView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		data = new DatabaseConnector(this);
		try {
			data.open();

			c = data.getAllContacts();

			startManagingCursor(c);

			c.moveToFirst();
			adapter = new ContactAdapter(this, c);

			setListAdapter(adapter);
		} catch (Exception e) {
			Log.e("Loi MainActivity==>", "Loi ham onCreate : mo database", e);
		}

		// header title Bar
		RelativeLayout layout = (RelativeLayout) findViewById(R.id.header_layout);
		Button btn = (Button) layout.findViewById(R.id.header_right_btn);
		registerForContextMenu(btn);
		btn.setOnClickListener(new android.view.View.OnClickListener() {
			@Override
			public void onClick(View v) {
				openContextMenu(v);
			}
		});

		ImageButton buttonContext = (ImageButton) layout
				.findViewById(R.id.header_left_btn);
		
		buttonContext.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				MainActivity.this.finish();
			}
		});

		// Action Menu --> Popup menu
		ActionItem actionItem1 = new ActionItem(getResources().getDrawable(
				R.drawable.ic_accept), "View detail", VIEW_DETAIL);
		ActionItem actionItem2 = new ActionItem(getResources().getDrawable(
				R.drawable.gmail), "Send email", SEND_MAIL);
		ActionItem actionItem3 = new ActionItem(getResources().getDrawable(
				R.drawable.phone), "Phone", PHONE);
		ActionItem actionItem4 = new ActionItem(getResources().getDrawable(
				android.R.drawable.ic_menu_mylocation), "View map", MAP);

		quickAction = new QuickAction(this);
		quickAction.addActionItem(actionItem1);
		quickAction.addActionItem(actionItem2);
		quickAction.addActionItem(actionItem3);
		quickAction.addActionItem(actionItem4);

		quickAction
				.setOnActionItemClickListener(new QuickAction.IOnActionItemClickListener() {

					@Override
					public void onItemClick(QuickAction source, int pos,
							int actionId) {

						DatabaseConnector databaseConnector = new DatabaseConnector(
								MainActivity.this);
						databaseConnector.open();
						Cursor cursor = databaseConnector.getOneContact(_id);

						switch (actionId) {

						case VIEW_DETAIL:
							Intent i = new Intent(MainActivity.this,
									ViewContact.class);
							i.putExtra(ROW_ID, _id);
							startActivity(i);
							break;

						case SEND_MAIL:

							if (cursor.moveToFirst()) {
								String email = cursor.getString(cursor
										.getColumnIndex(COLUMNS[4]));

								Intent emailIntent = new Intent(
										MainActivity.this,
										SendEmailActivity.class);
								emailIntent.putExtra(COLUMNS[4], email);
								startActivity(emailIntent);
							}

							databaseConnector.close();

							break;

						case PHONE:

							if (cursor.moveToFirst()) {
								String phone = "tel:"
										+ cursor.getString(cursor
												.getColumnIndex(COLUMNS[3]));
								Intent intent = new Intent(Intent.ACTION_DIAL,
										Uri.parse(phone));
								startActivity(intent);
							}
							break;

						case MAP:
							try {

								String geoCode = "geo:41.5020952,-81.6789717";
								Intent intent = new Intent(Intent.ACTION_VIEW,
										Uri.parse(geoCode));
								startActivity(intent);
							} catch (Exception e) {
								e.printStackTrace();
							}

							break;
						}
					}
				});

		quickAction.setOnDismissListener(new PopupWindow.OnDismissListener() {

			@Override
			public void onDismiss() {
				imageView.setImageResource(R.drawable.ic_list_more);
			}
		});

		getListView().setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {

				_id = arg3;
				Toast.makeText(getBaseContext(), "Hello you " + arg3,
						Toast.LENGTH_SHORT).show();
				Intent i = new Intent(MainActivity.this, ViewContact.class);
				i.putExtra(ROW_ID, _id);
				startActivity(i);
				return true;
			}
		});
	}
	
	public void onclick(View v) {
		switch (v.getId()) {
		
		case R.id.btnNew:
			Intent i = new Intent(this, AddEditContact.class);
			startActivity(i);
			break;

		case R.id.btnAbout:
			Builder bui = new Builder(this);
			bui.setTitle("About").setMessage("I'm Google")
					.setIcon(R.drawable.contact2).setPositiveButton("OK", null)
					.show();
			break;
		case R.id.btnClose:
			System.exit(0);
		default:
			break;
		}
		
	}

	@Override
	protected void onResume() {
		super.onResume();
		new GetContactsTask().execute();
	}

	@Override
	protected void onStop() {
		super.onStop();

		if (c != null) {
			c.deactivate();
			stopManagingCursor(c);
			adapter.changeCursor(null);
		}

		data.close();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.addressbook_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {

		case R.id.addContactItem:
			Intent i = new Intent(this, AddEditContact.class);
			startActivity(i);
			break;

		case R.id.About:
			Builder bui = new Builder(this);
			bui.setTitle("About").setMessage("I'm Google")
					.setIcon(R.drawable.contact2).setPositiveButton("OK", null)
					.show();
			break;

		case R.id.Close:
			System.exit(0);

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {

		getMenuInflater().inflate(R.menu.addressbook_menu, menu);
		menu.setHeaderTitle("Options");
		menu.setHeaderIcon(android.R.drawable.btn_star_big_on);
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {

		switch (item.getItemId()) {

		case R.id.addContactItem:
			Intent i = new Intent(this, AddEditContact.class);
			startActivity(i);
			break;

		case R.id.About:
			Builder bui = new Builder(this);
			bui.setTitle("About").setMessage("I'm Google")
					.setIcon(R.drawable.contact2).setPositiveButton("OK", null)
					.show();
			break;

		case R.id.Close:
			System.exit(0);

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);

		_id = id;

		imageView = (ImageView) v.findViewById(R.id.i_more);
		imageView.setImageResource(android.R.drawable.btn_star_big_on);
		quickAction.show(v);
	}

	private class GetContactsTask extends AsyncTask<Void, Cursor, Object> {

		DatabaseConnector databaseConnector = new DatabaseConnector(
				MainActivity.this);
		ProgressDialog pd;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();

			pd = ProgressDialog.show(MainActivity.this, "", "loading...");
		}

		@Override
		protected Cursor doInBackground(Void... params) {
			databaseConnector.open();
			return databaseConnector.getAllContacts();
		}

		@Override
		protected void onPostExecute(Object result) {
			super.onPostExecute(result);

			adapter.changeCursor((Cursor) result);
			databaseConnector.close();
			pd.dismiss();
		}

	}

}
